package com.leyou.auth.service;

import com.leyou.auth.client.UserClient;
import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.entity.UserInfo;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.user.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtProperties pro;

    /**
     * 认证加密的service
     *
     * @param username
     * @param password
     * @return
     */
    public String authentication(String username, String password) {
        try {
            // 调用feign的服务来查询user-service里的的query方法，验证用户名和密码是否正确
            User user = this.userClient.queryUser(username, password);
            if (user == null) {
                return null;
            }
            // 如果正确，对数据进行jwt和rsa的私钥进行加密生成token返回。。
            return JwtUtils.generateToken(new UserInfo(user.getId(), user.getUsername()),
                    pro.getPrivateKey(), pro.getExpire());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
